package nccloud.web.uapbd.ref.userdef;

import java.util.Map;

import nc.bs.logging.Logger;
import nc.md.IMDQueryFacade;
import nc.md.MDBaseQueryFacade;
import nc.md.model.IBean;
import nc.md.model.ITable;
import nc.vo.pub.BusinessException;
import nccloud.commons.lang.StringUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.processor.refgrid.RefQueryInfo;
import nccloud.framework.web.ui.meta.RefMeta;
import nccloud.framework.web.ui.meta.TreeRefMeta;
import nccloud.pubitf.platform.db.SqlParameterCollection;
import nccloud.pubitf.web.refer.INCCRefQry;
import nccloud.web.refer.DefaultGridRefAction;

public class DefdocGridRef extends DefaultGridRefAction {
	public DefdocGridRef() {
		setShowDisabledData(Boolean.valueOf(false));
		setUnitPkKey("pk_org");
	}

	public String getExtraSql(RefQueryInfo refQueryInfo, RefMeta refMeta) {
		String sql = "";
		Map param = refQueryInfo.getQueryCondition();
		
		if(StringUtils.isNotEmpty((String) param.get("whereSql"))) {
			sql = " and " + (String) param.get("whereSql");
		}
		sql = sql +" and pk_defdoclist=?";
		return sql;
	}

	public SqlParameterCollection getExtraSqlParameter(RefQueryInfo refQueryInfo, RefMeta refMeta) {
		SqlParameterCollection para = new SqlParameterCollection();

		para.addChar(getPk_defdoclist(refQueryInfo));

		return para;
	}

	protected String getPk_defdoclist(RefQueryInfo refQueryInfo) {
		return getQueryValue(refQueryInfo, "pk_defdoclist");
	}

	public TreeRefMeta getRefMeta(RefQueryInfo refQueryInfo) {
		try {
			setResourceCode(((INCCRefQry) ServiceLocator.find(INCCRefQry.class))
					.getDefdocRefResourceId(getPk_defdoclist(refQueryInfo)));
		} catch (BusinessException ex) {
			Logger.error(ex.getMessage(), ex);
		}

		setMdClassId(getPk_defdoclist(refQueryInfo));

		TreeRefMeta refMeta = new TreeRefMeta();

		refMeta.setCodeField("code");
		refMeta.setNameField("name");
		refMeta.setPkField("pk_defdoc");
		refMeta.setExtraFields(new String[] { "code", "name", "shortname", "mnecode", "enablestate" });

		refMeta.setMutilLangNameRef(true);
		refMeta.setTableName(getTableName(getPk_defdoclist(refQueryInfo)));

		return refMeta;
	}

	protected String getTableName(String pk_defdoclist) {
		if (StringUtils.isNotBlank(pk_defdoclist)) {
			try {
				IBean bean = MDBaseQueryFacade.getInstance().getBeanByID(pk_defdoclist);

				if (bean != null)
					return bean.getTable().getName();
			} catch (Exception e) {
				Logger.error(e);
			}
		}

		return "bd_defdoc";
	}
}